package scriptrunner.execution.cloud;

import java.io.Serializable;

import communication.MessageHelper;
import communication.ParameterizedMessage;
import communication.ParameterizedMessageImpl;

import scriptrunner.execution.ExecuteErrorException;
import scriptrunner.execution.FuncSignature;
import scriptrunner.execution.Function;
import scriptrunner.execution.ParameterList;
import scriptrunner.execution.Session;
import scriptrunner.execution.ValueObject;

public class CloudFunctionProxy extends Function implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -3777466678765814241L;
	
	private Function function;
	
	private Session session;

	public CloudFunctionProxy(Function concreteFunction) {
		function = concreteFunction;
	}

	/**
	 * Remote execute the underlining function.
	 */
	@Override
	public ValueObject Execute(Session se) throws ExecuteErrorException {
		this.session = se;
		ParameterizedMessage msg = new ParameterizedMessageImpl("ScriptExecutionService::Function::Execute");
		msg.setAttachment(this);
		
		ParameterizedMessage response = CloudManager.getCloudManager("GreenCloud").sendMessageToRandomSlave(msg);
		
		if (MessageHelper.getNonNullParameter(response, MessageHelper.RESULT).equals(MessageHelper.SUCCESS)) {
			
			CloudResult result = (CloudResult) response.getAttachment();
			
			this.session.sync(result.getSession());
			
			return result.getValueObject();
		} else {
			return null;
		}
	}
	
	/**
	 * Local execute.
	 */
	public ValueObject Execute() throws ExecuteErrorException {
		return this.function.Execute(this.session);
	}
	
	/**
	 * @return
	 */
	@Override
	public ParameterList getParameterList() {
		return function.getParameterList();
	}

	/**
	 * 
	 * @return
	 */
	@Override
	public FuncSignature GetSignature() {
		return function.GetSignature();
	}
	
	public Function getFunction() {
		return this.function;
	}
	
	public Session getSession() {
		return this.session;
	}
}
